﻿var globalNewslistItems;
var globalNewsquery;
var globalNewstargetList;
var globalNewsClientContext;
var globalNewsIsLoaded = false;
var globalNewsTopNewsItemId = 0;
(function ($) {

    $(function () {
        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", getThumbnailPreview('globaltopnewscategory', 'globalothernewscategory '));
            $.getScript(scriptbase + "SP.Taxonomy.js", loadmoredata());
        });
    });

    this.loadmoredata = function () {
        $(window).scroll(function () {
            if ($(window).scrollTop() - ($(document).height() - $(window).height() - 190) < 90 && $(window).scrollTop() - ($(document).height() - $(window).height() - 190) > 0) {
                if (globalNewsIsLoaded) {
                    getmorenewscategories('globalothernewscategory ');
                }
            }
        });
    };
    this.getThumbnailPreview = function (idlastnews, idothernews) {
        globalNewsIsLoaded = false;
        $('#globalloading').show();
        var thumbnailSiteUrl = window.location.protocol + '//' + window.location.host + '/teams/OurVoiceHN/News/';
        var thumbnailClientContext = new SP.ClientContext(thumbnailSiteUrl);
        var thumbnailPostesList = thumbnailClientContext.get_web().get_lists().getByTitle('Posts');
        var thumbnailquery = new SP.CamlQuery();
        var catId = getParameterByName('CategoryId');
        if (catId == "") {
            thumbnailquery.set_viewXml('<View><Query><Where><And><And><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq><Eq><FieldRef Name=\'Top_x0020_News\' /><Value Type=\'Boolean\'>1</Value></Eq></And><Eq><FieldRef Name=\'Subject_x0020_Type\' /><Value Type=\'Choice\'>Global News</Value></Eq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>1</RowLimit> </View>');
        }
        else {
            thumbnailquery.set_viewXml('<View><Query><Where><And><And><And><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq><Eq><FieldRef Name=\'Top_x0020_News\' /><Value Type=\'Boolean\'>1</Value></Eq></And><Eq><FieldRef Name=\'PostCategory\' LookupId=\'True\' /><Value Type=\'LookupMulti\'>' + parseInt(catId) + '</Value></Eq></And><Eq><FieldRef Name=\'Subject_x0020_Type\' /><Value Type=\'Choice\'>Global News</Value></Eq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>1</RowLimit></View>');
        }
        var thumbnailItemCollection = thumbnailPostesList.getItems(thumbnailquery);
        thumbnailClientContext.load(thumbnailItemCollection);
        thumbnailClientContext.executeQueryAsync(
            function () {
                $('#' + idlastnews).html('');
                $('#' + idothernews).html('');
                var topnewsItemId = 0;
                var listEnumerator = thumbnailItemCollection.getEnumerator();
                while (listEnumerator.moveNext()) {
                    var item = listEnumerator.get_current();
                    var url = thumbnailSiteUrl + 'Lists/Posts/Post.aspx?ID=' + item.get_item('ID');
                    var categoryLink = '#';
                    var categoryname = '';
                    if (item.get_item('PostCategory')[0] != null) {
                        categoryLink = thumbnailSiteUrl + 'Lists/Categories/Category.aspx?CategoryId=' + item.get_item('PostCategory')[0].get_lookupId();
                        categoryname = item.get_item('PostCategory')[0].get_lookupValue();
                    }
                    topnewsItemId = parseInt(item.get_item("ID") || 0);
                    //build number of comments
                    var numCommentsValue = item.get_item('NumComments');
                    var totalcomment = numCommentsValue.get_lookupId();
                    //build latest news
                    var news = buildnewscategorylatest(item.get_item('PublishingPageIcon'), url, item.get_item('Title'), item.get_item('Summary'), item.get_item('AuthorName'), new Date(item.get_item('PublishedDate')), categoryLink, categoryname, totalcomment);
                    $('#' + idlastnews).append(news);
                }
                globalNewsTopNewsItemId = topnewsItemId;
                //Get other news
                getnewscategories(idothernews, topnewsItemId);

            }, function (sender, args) {
                console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };

    this.getnewscategories = function (idothernews, topnewsItemId) {
        globalNewsIsLoaded = false;
        var siteUrl = window.location.protocol + '//' + window.location.host + '/teams/OurVoiceHN/News/';
        globalNewsClientContext = new SP.ClientContext(siteUrl);
        globalNewstargetList = globalNewsClientContext.get_web().get_lists().getByTitle('Posts');
        globalNewsquery = new SP.CamlQuery();
        var catId = getParameterByName('CategoryId');

        if (catId == "") {
            globalNewsquery.set_viewXml('<View><Query><Where><And><And><Neq><FieldRef Name=\'ID\' /><Value Type=\'Counter\'>' + topnewsItemId + '</Value></Neq><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq></And><Eq><FieldRef Name=\'Subject_x0020_Type\' /><Value Type=\'Choice\'>Global News</Value></Eq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>5</RowLimit></View>');
        }
        else {
            globalNewsquery.set_viewXml('<View><Query><Where><And><And><And><Neq><FieldRef Name=\'ID\' /><Value Type=\'Counter\'>' + topnewsItemId + '</Value></Neq><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq></And><Eq><FieldRef Name=\'PostCategory\' LookupId=\'True\' /><Value Type=\'LookupMulti\'>' + parseInt(catId) + '</Value></Eq></And><Eq><FieldRef Name=\'Subject_x0020_Type\' /><Value Type=\'Choice\'>Global News</Value></Eq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>5</RowLimit></View>');
        }
        globalNewslistItems = globalNewstargetList.getItems(globalNewsquery);
        globalNewsClientContext.load(globalNewslistItems);
        globalNewsClientContext.executeQueryAsync(
            function () {
                globalNewsIsLoaded = true;
                $('#' + idothernews).html('');
                var listEnumerator = globalNewslistItems.getEnumerator();

                while (listEnumerator.moveNext()) {
                    var item = listEnumerator.get_current();
                    var newItemId = parseInt(item.get_item("ID") || 0);
                    if ($.trim(newItemId.toString()) !== $.trim(topnewsItemId.toString())) {
                        var url = siteUrl + 'Lists/Posts/Post.aspx?ID=' + item.get_item('ID');
                        var categoryLink = '#';
                        var categoryname = '';
                        if (item.get_item('PostCategory')[0] != null) {
                            categoryLink = siteUrl + 'Lists/Categories/Category.aspx?CategoryId=' + item.get_item('PostCategory')[0].get_lookupId();
                            categoryname = item.get_item('PostCategory')[0].get_lookupValue();
                        }
                        //build number of comments
                        var numCommentsValue = item.get_item('NumComments');
                        var totalcomment = numCommentsValue.get_lookupId();
                        var othernewsitem = buildothernewscategory(item.get_item('PublishingPageIcon'), url, item.get_item('Title'), item.get_item('Summary'), item.get_item('AuthorName'), new Date(item.get_item('PublishedDate')), categoryLink, categoryname, totalcomment);;
                        $('#' + idothernews).append(othernewsitem);
                    }
                }
                $('#globalloading').hide();
            }, function (sender, args) {
                console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };

    this.getmorenewscategories = function (idothernews, pageindex) {
        globalNewsIsLoaded = false;
        var siteUrl = window.location.protocol + '//' + window.location.host + '/teams/OurVoiceHN/News/';
        var position = globalNewslistItems.get_listItemCollectionPosition();
        if (position != null) {
            $('#globalloading').show();
            globalNewsquery = new SP.CamlQuery();
            var catId = getParameterByName('CategoryId');
            if (catId == "") {
                globalNewsquery.set_viewXml('<View><Query><Where><And><And><Neq><FieldRef Name=\'ID\' /><Value Type=\'Counter\'>' + topnewsItemId + '</Value></Neq><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq></And><Eq><FieldRef Name=\'Subject_x0020_Type\' /><Value Type=\'Choice\'>Global News</Value></Eq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>5</RowLimit></View>');
            }
            else {
                globalNewsquery.set_viewXml('<View><Query><Where><And><And><And><Neq><FieldRef Name=\'ID\' /><Value Type=\'Counter\'>' + topnewsItemId + '</Value></Neq><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq></And><Eq><FieldRef Name=\'PostCategory\' LookupId=\'True\' /><Value Type=\'LookupMulti\'>' + parseInt(catId) + '</Value></Eq></And><Eq><FieldRef Name=\'Subject_x0020_Type\' /><Value Type=\'Choice\'>Global News</Value></Eq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>5</RowLimit></View>');
            }
            globalNewsquery.set_listItemCollectionPosition(position);
            globalNewslistItems = globalNewstargetList.getItems(globalNewsquery);
            globalNewsClientContext.load(globalNewslistItems);
            globalNewsClientContext.executeQueryAsync(function () {
                globalNewsIsLoaded = true;               
                var listEnumerator = globalNewslistItems.getEnumerator();
                while (listEnumerator.moveNext()) {
                    var item = listEnumerator.get_current();
                    var url = siteUrl + 'Lists/Posts/Post.aspx?ID=' + item.get_item('ID');
                    var categoryLink = '#';
                    var categoryname = '';
                    if (item.get_item('PostCategory')[0] != null) {
                        categoryLink = siteUrl + 'Lists/Categories/Category.aspx?CategoryId=' + item.get_item('PostCategory')[0].get_lookupId();
                        categoryname = item.get_item('PostCategory')[0].get_lookupValue();
                    }
                    //build number of comments
                    var numCommentsValue = item.get_item('NumComments');
                    var totalcomment = numCommentsValue.get_lookupId();
                    var othernewsitem = buildothernewscategory(item.get_item('PublishingPageIcon'), url, item.get_item('Title'), item.get_item('Summary'), item.get_item('AuthorName'), new Date(item.get_item('PublishedDate')), categoryLink, categoryname, totalcomment);;
                    $('#' + idothernews).append(othernewsitem).fadeIn(1000);
                }
                $('#globalloading').hide();

            }, function (sender, args) {
                console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
       );
        }

    };

    this.buildnewscategorylatest = function (imageurl, itemurl, title, content, username, publishDate, categorylink, categoryname, totalcomment) {
        if (totalcomment == "") {
            totalcomment = "0";
        }

        var imgurl;
        if (imageurl != null && $(imageurl).attr('src') != '') {
            imgurl = $(imageurl).attr('src');
        }
        else {
            imgurl = '/teams/OurVoiceHN/Style Library/Images/default_image.gif';
        }

        if (title == null) {
            title = "";
        }

        if (content == null) {
            content = "";
        }

        if (content.length > 500) {
            content = content.substring(0, 500);
        }
        if (username == null)
            username = "";
        var result = '<a href="' + itemurl + '"><img class="img-responsive" src="' + imgurl + '"></a>';
        result += '<div class="newscontent caption">';

        result += '<h3 class="title">';
        result += '<a href="' + itemurl + '">' + title + '</a>';
        result += '</h3>';

        result += '<h5 class="newstime">';
        result += 'by ' + username + ' | ';
        result += '<span>' + totalcomment + ' comments</span>';
        result += '</h5>';

        result += '<p class="content">' + content;
        result += '<span><a href="' + itemurl + '"> ...More</a><span>';
        result += '</p>';

        result += '</div>';
        return result;
    };

    this.buildothernewscategory = function (imageurl, itemurl, title, content, username, publishDate, categorylink, categoryname, totalcomment) {
        if (totalcomment == "") {
            totalcomment = "0";
        }

        var imgurl;
        if (imageurl != null && $(imageurl).attr('src') != '') {
            imgurl = $(imageurl).attr('src');
        }
        else {
            imgurl = '/teams/OurVoiceHN/Style Library/Images/default_image.gif';
        }

        if (title == null) {
            title = "";
        }

        if (title.length > 40) {
            title = title.substring(0, 40) + '...';
        }

        if (content == null) {
            content = "";
        }

        if (content.length > 150) {
            content = content.substring(0, 150);
        }

        if (username == null)
            username = "";
        var result = '<div class="newsitem col-sm-12 col-md-12 col-lg-12">';

        result += '<div class="row">';

        result += '<div class="newsleft col-sm-6 col-md-6 col-lg-6">';
        result += '<a href="' + itemurl + '"><img class="img-responsive" src="' + imgurl + '" /></a>';
        result += '</div>';

        result += '<div class="newsright col-sm-6 col-md-6 col-lg-6">';

        result += '<h4 class="title">';
        result += '<a href="' + itemurl + '">' + title + '</a>';
        result += '</h4>';

        result += '<h5 class="newstime">';
        result += 'by ' + username + ' | ';
        result += '<span>' + totalcomment + ' comments</span>';
        result += '</h5>';

        result += '<p class="content">' + content + '</p>';
        result += '<a class="viewMore" href="' + itemurl + '">More</a>';
        result += '</div>';
        result += '</div>';

        result += '</div>';
        return result;
    };

    this.formatAMPM = function (date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        return strTime;
    };
    this.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };
    this.updateQueryStringParameter = function (uri, key, value) {
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        } else {
            return uri + separator + key + "=" + value;
        }
    };
    /*end javascript for get news category*/
    /*=======================================*/
}).call(this, jQuery);